<template>
  <div>
    <div id="mapContainer"></div>
  </div>
</template>
<script>
export default {
  data() {
    return {}
  },
  created() {
    // 已载入高德地图API，则直接初始化地图
    if (window.AMap && window.AMapUI) {
      this.initMap()
    // 未载入高德地图API，则先载入API再初始化
    } else {
      // 载入高德地图和UI组件
      Promise.all([
        remoteLoad(`//webapi.amap.com/maps?v=1.3&key=${MapKey}`),
        remoteLoad('//webapi.amap.com/ui/1.0/main.js')
      ]).then(() => {
        this.initMap()
      })
    }
  },
  methods: {
    initMap() {
      var _this = this
      let AMapUI = this.AMapUI = window.AMapUI
      let AMap = this.AMap = window.AMap
      AMapUI.loadUI(['misc/PositionPicker'], PositionPicker => {
        let mapConfig = {
          zoom: 16,
          cityName: MapCityName
        }
        if (this.lat && this.lng) {
          mapConfig.center = [this.lng, this.lat]
        }
        let mapObj = new AMap.Map('mapContainer', { // 'map-location'是对应页面盒子的id
          resizeEnable: true, // 自适应大小
          zoom: 13 // 初始视窗
        })
      })
      mapObj.plugin('AMap.Geolocation', function() {
        geolocation = new AMap.Geolocation({
          /* timeout: 10000,
          GeoLocationFirst: false,
          maximumAge: 0 // 定位结果缓存0毫秒，默认：0 */
          enableHighAccuracy: true, // 是否使用高精度定位，默认:true
          timeout: 10000, // 超过10秒后停止定位，默认：无穷大
          buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          zoomToAccuracy: true, // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          buttonPosition: 'RB'
        })
        mapObj.addControl(geolocation)
        geolocation.getCurrentPosition()
        AMap.event.addListener(geolocation, 'complete', _this.onComplete) // 返回定位信息
        AMap.event.addListener(geolocation, 'error', _this.onError)
      })
    },
    onComplete(data) {
      var str = ['定位成功']
      str.push('经度：' + data.position.getLng())
      str.push('纬度：' + data.position.getLat())
      if (data.accuracy) {
        str.push('精度：' + data.accuracy + ' 米')
      } // 如为IP精确定位结果则没有精度信息
      str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'))
      console.log(str)
    },
    // 解析定位错误信息
    onError(data) {
      alert('获取您当前位置失败！')
    }
  }
}
</script>

